# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution	
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from osv import fields,osv
from osv.orm import except_orm
import tools
import time
import netsvc

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(server_info,context, body):
    m_server = server_info['server']
    user = server_info['user']
    password = server_info['password']
    
    from_email = server_info['from_email'] + " <" + server_info['email'] + ">" 
    for xyz in context:
        
        toaddr = xyz['To']
        other_info = xyz['cc_bcc']
        attr_file = xyz['file']
        subject =xyz['Subject']
        
        cc=[]
        bcc=[]
        if 'cc' in other_info:
            cc = other_info['cc']
        if 'bcc' in other_info:
            bcc = other_info['bcc']
                
        try:
            toaddr = eval(toaddr)
        except:
            toaddr = toaddr
        
        try:
            cc = eval(cc)
        except:
            cc = cc
            
        try:
            bcc = eval(bcc)
        except:
            bcc = bcc        
                    
        if type(toaddr)!=type([]):
            toaddr = [toaddr]
            
        if type(cc)!=type([]):
            cc = [cc]
        if type(bcc)!=type([]):
            bcc = [bcc]
            
        toaddrs = toaddr + cc + bcc
        
        msg = MIMEMultipart()
        msg['From'] = from_email
        msg['To'] = COMMASPACE.join(toaddr)
        msg['CC'] = ",".join(cc)
        msg['Subject'] = subject
        
        try:                
            msg.attach(MIMEText(body.encode('utf8') or '', _charset='utf-8', _subtype="html"))
        except:
            msg.attach(MIMEText(body or '', _charset='utf-8', _subtype="html"))
        
        #msg.attach(MIMEText(body))
        
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(attr_file,"rb").read())
        Encoders.encode_base64(part)
        
        if attr_file.upper().find("BUDGETBALANCESHEET"):
            attr_file = "BudgetBalanceSheet"+time.strftime("%d.%b.%Y")+".pdf"
            
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % attr_file)
        
        msg.attach(part)

        smtp = smtplib.SMTP(m_server)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        
        smtp.login(str(user),str(password))

        smtp.sendmail(server_info['email'], toaddrs, msg.as_string())
        smtp.close()

def get_value(type_of_value=False,format=False):
    type_of_value = type_of_value.upper().strip()
    if type_of_value=="CURRENT_DATE":
        if format:
            return time.strftime(format)
        else:
            return time.strftime("%d/%b/%Y")

class scheduler_notification(osv.osv):
    _name='scheduler.notification'
    _description="Scheduler Notification"
            
    _columns = {
                'code':fields.char("Code",size=250,required=True),
                'ir_cron_id':fields.many2one('ir.cron','Scheduler',required=True),
                'name':fields.char("Name",size=250),
                'subject':fields.char('Subject',size=250,required=True),
                'body':fields.text("Body",required=True),
                'send_users_ids':fields.one2many('send.users.list','scheduler_id','Send Users List'),
                'group_ids':fields.one2many('groups.list','scheduler_id','Send Groups List'),
                }
    _sql_constraints = [('code_unique_name', 'unique (code)', 'The code of the project must be unique !')]
    
    
    def _check_overbudget_sent(self, cr, uid, code='',use_new_cursor=False, context={}):
        
        def createReport(cr, uid, report, ids,my_model,attach_name=False):
            files = ''
            if ids:
                #try:
                file_attach_name='Report.pdf'
                if attach_name:
                    file_attach_name=attach_name+".pdf"
                service = netsvc.LocalService(report)
                (result, format) = service.create(cr, uid, ids,my_model , {})
                report_file = '/tmp/'+ file_attach_name
                fp = open(report_file,'wb+')
                try:
                    fp.write(result);
                finally:
                    fp.close();
                files = report_file  
                #except Exception,e:
            return files
#        cr.execute("Update ir_cron set active=False where name='Send Email'")
        mail_obj = self.pool.get('email.smtpclient')
        smtp_clt_id = mail_obj.search(cr,uid,[('name','=','Kinden Reminder')])
        server_info = mail_obj.read(cr,uid,smtp_clt_id,['server','user','password','from_email','email'])
        if len(smtp_clt_id)>=1:
            smtp_clt_id = smtp_clt_id[0]
        this_id = self.search(cr,uid,[('code','=',code)])
        notification_lists = self.browse(cr,uid,this_id)
        cc=[]
        bcc=[]
        eml_to=[]
        
        if notification_lists:
            body = notification_lists[0].body
            subject = notification_lists[0].subject
            for temp_u in notification_lists[0].send_users_ids:
                if temp_u.sendtype=='to':
                    eml_to.append(temp_u.user_id.email_address)
                elif temp_u.sendtype=='cc':
                    cc.append(temp_u.user_id.email_address)
                else:
                    bcc.append(temp_u.user_id.email_address)
            for temp_g in notification_lists[0].group_ids:
                for temp_u in temp_g.group_id.users:
                    if temp_g.sendtype=='to':
                        eml_to.append(temp_u.email_address)
                    elif temp_g.sendtype=='cc':
                        cc.append(temp_u.email_address)
                    else:
                        bcc.append(temp_u.email_address)                        
            cc_bcc={'onemail':True,'later':True}
            if cc:
                cc_bcc['cc']=cc
            if bcc:
                cc_bcc['bcc']=bcc
            if body.find('$CURRENT_DATE$'):
                body=body.replace('$CURRENT_DATE$',get_value('CURRENT_DATE'))
            prj_over_ids=[]
#            prj_obj = self.pool.get('kdvn.project')
#            prj_ids = prj_obj.search(cr,uid,[('project_type','!=','closed')]) 
#            for prj in prj_obj.browse(cr,uid,prj_ids):
#                for bg_info in prj.budget_data_ids:
#                    if bg_info.over:
#                        prj_over_ids.append(prj.id)
#                        break
            cr.execute("Select kp.id,ru.name from kdvn_project kp left join res_users ru on kp.project_manager_id=ru.id where project_type<>'closed' and coalesce(project_manager_id,0)>0 order by ru.name")
            #raise osv.except_osv("E",prj_over_ids)
            prj_name_using=" "
            prj_ids_using=[]
            Check_First = 0               
            #raise osv.except_osv("E","CC:"+str(cc_bcc))
            list_prjs_temp=[]
            attch_file=''
            for prj_id,prj_name in cr.fetchall():
                if prj_name_using==prj_name:
                   prj_ids_using.append(prj_id)
                else:
                    if Check_First == 0: #Lan dau tien
                        Check_First = 1
                    else:                        
                        new_subject = subject.replace('$PROJECT_MANAGER$','Project Manager: Mr. '+ prj_name_using)
                        attch_file = createReport(cr,uid,'report.budget.balance.sheet.rev01',prj_ids_using,{'model':'kdvn.project'},'BudgetBalanceSheet'+prj_name_using.replace(" ",""))
                        #reports=['report.budget.balance.sheet.rev01',prj_ids_using,{'model':'kdvn.project'},'BudgetBalanceSheet'+time.strftime("%d.%b.%Y")]
                        list_prjs_temp.append({'file':attch_file,'Subject':new_subject,'To':eml_to,'cc_bcc':cc_bcc})
                        #a=mail_obj.send_email(cr,uid,smtp_clt_id,eml_to,new_subject,body,attch_file,[],cc_bcc)
                    prj_ids_using=[prj_id]
                    prj_name_using=prj_name
            if Check_First==1:
                new_subject = subject.replace('$PROJECT_MANAGER$','Project Manager: Mr. '+ prj_name_using)
                #reports=['report.budget.balance.sheet.rev01',prj_ids_using,{'model':'kdvn.project'},'BudgetBalanceSheet'+time.strftime("%d.%b.%Y")]
                attch_file = createReport(cr,uid,'report.budget.balance.sheet.rev01',prj_ids_using,{'model':'kdvn.project'},'BudgetBalanceSheet'+prj_name_using.replace(" ",""))
                list_prjs_temp.append({'file':attch_file,'Subject':new_subject,'To':eml_to,'cc_bcc':cc_bcc})
                #a=mail_obj.send_email(cr,uid,smtp_clt_id,eml_to,new_subject,body,attch_file,[],cc_bcc)
#            for x in list_prjs_temp:
#                a=mail_obj.send_email(cr,uid,smtp_clt_id,eml_to,x['Subject'],body,x['file'],[],cc_bcc)
            if type(server_info)==type([]):
                send_mail(server_info[0],list_prjs_temp,body)
            else:
                send_mail(server_info,list_prjs_temp,body)
#            fo=open("/home/openerp/ab.txt","a")
#            fo.write(str(len(list_prjs_temp)))
#            fo.close()
        return True

scheduler_notification()

class send_users_list(osv.osv):
    _name='send.users.list'
    _description="Send User List"
    
    _columns = {
                'user_id':fields.many2one("res.users",'User',required=True),
                'sendtype':fields.selection([('to','To'),('cc','CC'),('bcc','BCC')],'Send Type',required=True),
                'scheduler_id':fields.many2one('scheduler.notification','Scheduler ID',required=True)
                }
    _sql_constraints = [('code_unique_name', 'unique (user_id,scheduler_id)', 'The code of the project must be unique !')]
    _defaults={
               'sendtype':lambda *x:'to'
               }
send_users_list()

class groups_list(osv.osv):
    _name='groups.list'
    _description="Groups List"
    
    _columns = {
                'group_id':fields.many2one("res.groups",'Group',required=True),
                'sendtype':fields.selection([('to','To'),('cc','CC'),('bcc','BCC')],'Send Type',required=True),
                'scheduler_id':fields.many2one('scheduler.notification','Scheduler ID',required=True)
                }
    _sql_constraints = [('code_unique_name', 'unique (group_id,scheduler_id)', 'The code of the project must be unique !')]
    _defaults={
               'sendtype':lambda *x:'to'
               }
groups_list()